package com.chixing.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.config.AlipayConfig;
import com.chixing.entity.Flow;
import com.chixing.entity.Myorder;
import com.chixing.service.IFlowService;
import com.chixing.service.IMyorderService;
import com.chixing.util.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * <p>
 * 流水表 前端控制器
 * </p>
 *
 * @author smith
 * @since 2025-09-22
 */
@CrossOrigin
@RestController
@RequestMapping("/flow")
public class FlowController {

    @Autowired
    private IMyorderService myorderService;
    @Autowired
    private IFlowService flowService;

    @GetMapping("{flowId}")
    public Result getById(@PathVariable("flowId") Integer flowId){
        return flowService.getDetailById(flowId);
    }

    //-----------------------调用支付宝支付
    @PostMapping
    public String alipay(@RequestBody Myorder myorder , HttpServletResponse response) throws AlipayApiException {
        System.out.println("支付alipay orderId = " + myorder.getOrderId());
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //创建api对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        //在公共参数中设置回调和通知地址
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String timeout_express = "1c";
        String body="";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + myorder.getOrderNum() + "\","
                + "\"total_amount\":\"" + myorder.getOrderPrice() + "\","
                + "\"subject\":\"" + myorder.getProductName() + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //调用支付宝接口并给出响应数据
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println("执行支付请求后，result:" + result );

        return result;
    }
    //---------------- 同步请求 支付宝调用接受后，数据响应，展示流水信息
    @GetMapping("alipayReturnNotice")
    public void alipayReturnNotice(HttpServletRequest request,HttpServletResponse response) throws IOException {
        System.out.println("同步请求，支付成功后，支付宝的返回数据是:" + request);
        //商户订单号
        //商户订单号
        String orderNum = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String payPrice = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("return orderNum:" + orderNum);
        System.out.println("return tradeNo:" + tradeNo);
        System.out.println("return payPrice:" + payPrice);

        //添加流水
        Myorder orders = (Myorder) myorderService.getByOrderNumber(orderNum).getData();
        Flow flow = new Flow();
        flow.setOrderId(orders.getOrderId());
        flow.setUserId(1);
        flow.setPaidPrice(orders.getOrderPrice());

        Result result = flowService.save(flow);
        flow = (Flow) result.getData();

        //页面跳转
        String vueUrl = "http://localhost:5173/flowDetail/" + flow.getFlowId();
        response.sendRedirect(vueUrl);
    }


    // 异步请求回调
    @PostMapping("alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        System.out.println("异步请求，支付成功后，支付宝的返回数据是：" + request);
        //商户订单号
        String orderNum = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //支付宝交易号
        String tradeNo = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        //付款金额
        String payPrice = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

        System.out.println("return orderNum:" + orderNum);
        System.out.println("return tradeNo:" + tradeNo);
        System.out.println("return payPrice:" + payPrice);

        //
        Myorder orders =(Myorder)  myorderService.getByOrderNumber(orderNum).getData();
        Flow flow = new Flow();
        flow.setOrderId(orders.getOrderId());


        // 添加流水 , 修改订单状态
        Result result = flowService.save(flow);
        return  "success";
    }


}
